package com.situ.stmall.manager.controller.api;

import com.github.pagehelper.PageInfo;
import com.situ.stmall.manager.entity.Category;
import com.situ.stmall.manager.entity.Goods;
import com.situ.stmall.manager.entity.Result;
import com.situ.stmall.manager.service.GoodsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/goods")
public class APIGoodsController {
    //自动注入Service层对象
    @Resource
    private GoodsService goodsService;

    /**
     * POST 添加
     */
    @PostMapping
    public Result add(@RequestBody Goods goods){
        try {
            int code = goodsService.add(goods);
            return  Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * Delete
     * @param id
     * @return
     */
    @DeleteMapping
    public Result remove(Integer id){
        try {
            int code = goodsService.remove(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * PUT
     */
    @PutMapping
    public Result edit(@RequestBody Goods goods){
        try {
            int code = goodsService.edit(goods);
            return  Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据id查询,通过路径url传递参数
     * GET
     */
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id){
        Goods goods = goodsService.getById(id);
        if(goods == null){
            return Result.error("ID不存在");
        }else{
            return Result.success(goods);
        }
    }

    /**
     * 查询 GET
     */
    @GetMapping
    public Result get(Integer page, Integer limit, Goods goods){
        if(page == null){
            List<Goods> list = goodsService.search(goods);
            return Result.success(list);
        }else{
            PageInfo pageInfo = goodsService.searchByPage(page,limit,goods);
            return Result.success(pageInfo);
        }

    }
}
